class Easy_Uploads {
    constructor(obj) {
        if (Object.prototype.toString.call(obj) !== '[object Object]') {
            throw new Error("需传入一个object参数")
        }else{
            if (!obj.file || !obj.viewer || !obj.button) {
                throw new Error("参数不全")
            }
        }
        this.fileObj = {}
        this.init(obj)
    }
    init (obj) {
        this.fileInput = document.querySelector(obj.file)
        this.previewer = document.querySelector(obj.viewer)
        this.send = document.querySelector(obj.button)
        this.fileInput.onchange = (e) => { this.fileChange(e, obj) }
        this.send.onclick = () => { this.callback(obj) }
    }
    fileChange (res, obj) {
        if (!this.fileInput.files[0]) { return }
        if (obj.change) {
            if (obj.change(res) == false) {
                return
            }
        }
        var _this = this
        var file = this.fileInput.files[0]
        var fileName = this.fileInput.files[0].name
        var img = document.createElement("img")
        img.classList.add("Easy_Uploads")
        this.previewer.innerHTML = ""
        this.previewer.appendChild(img)
        var reader = new FileReader()
        reader.onload = (function (aImg) {
            return function (e) {
                aImg.src = e.target.result
                _this.fileObj = {
                    file: e.target.result,
                    fileName
                }
            }
        })(img)
        reader.readAsDataURL(file)
    }
    dataURLtoFile (dataUrl, fileName) {
        var arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n); 1
        }
        return new File([u8arr], fileName, { type: mime });
    }
    callback (obj) {
        if (JSON.stringify(this.fileObj) == "{}") { return }
        let fileData = this.dataURLtoFile(this.fileObj.file, this.fileObj.fileName)
        if (obj.success) {
            obj.success({
                base64: this.fileObj.file,
                fileName: this.fileObj.fileName,
                file: fileData
            })
        }
    }
}